//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.farm.authority.service.impl;

import com.farm.authority.dao.OrganizationDaoInter;
import com.farm.authority.dao.PostDaoInter;
import com.farm.authority.dao.PostactionDaoInter;
import com.farm.authority.dao.UserDaoInter;
import com.farm.authority.dao.UserpostDaoInter;
import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Post;
import com.farm.authority.domain.Postaction;
import com.farm.authority.service.OrganizationServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.time.TimeTool;
import com.farm.web.easyui.EasyUiTreeNode;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class OrganizationServiceImpl implements OrganizationServiceInter {
	@Resource
	private OrganizationDaoInter organizationDao;
	@Resource
	private PostDaoInter postDao;
	@Resource
	private UserpostDaoInter userpostDao;
	@Resource
	private PostactionDaoInter postactionDao;
	@Resource
	private UserDaoInter userDao;
	private static final Logger log = Logger.getLogger(OrganizationServiceImpl.class);

	public OrganizationServiceImpl() {
	}

	@Transactional
	public Organization insertOrganizationEntity(Organization entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setMuser(user.getId());
		entity.setUtime(TimeTool.getTimeDate14());
		entity.setState("1");
		if (entity.getParentid() == null) {
			entity.setParentid("NONE");
		}

		entity.setTreecode("NONE");
		entity = this.organizationDao.insertEntity(entity);
		this.initTreeCode(entity.getId());
		return entity;
	}

	@Transactional
	public Organization editOrganizationEntity(Organization entity, LoginUser user) {
		Organization entity2 = this.organizationDao.getEntity(entity.getId());
		entity2.setMuser(user.getId());
		entity2.setUtime(TimeTool.getTimeDate14());
		entity2.setType(entity.getType());
		entity2.setSort(entity.getSort());
		entity2.setState(entity.getState());
		entity2.setComments(entity.getComments());
		entity2.setName(entity.getName());
		this.organizationDao.editEntity(entity2);
		return entity2;
	}

	@Transactional
	public void deleteOrganizationEntity(String id, LoginUser user) {
		if (this.organizationDao.selectEntitys(DBRule.addRule(new ArrayList(), "parentid", id, "=")).size() > 0) {
			throw new RuntimeException("不能删除该节点，请先删除其子节点");
		} else {
			Iterator var4 = this.postDao.selectEntitys((new DBRule("ORGANIZATIONID", id, "=")).getDBRules()).iterator();

			while (var4.hasNext()) {
				Post post = (Post) var4.next();
				this.deletePostEntity(post.getId(), user);
			}

			this.organizationDao.deleteEntity(this.organizationDao.getEntity(id));
		}
	}

	@Transactional
	public Organization getOrganizationEntity(String id) {
		return id == null ? null : this.organizationDao.getEntity(id);
	}

	@Transactional
	public DataQuery createOrganizationSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query, "ALONE_AUTH_ORGANIZATION",
				"ID,TYPE,SORT,PARENTID,MUSER,CUSER,STATE,UTIME,CTIME,COMMENTS,NAME,TREECODE");
		return dbQuery;
	}

	@Transactional
	public void deletePostEntity(String id, LoginUser user) {
		String[] ids = id.split(",");
		String[] var7 = ids;
		int var6 = ids.length;

		for (int var5 = 0; var5 < var6; ++var5) {
			String id1 = var7[var5];
			this.userpostDao.deleteEntitys((new DBRule("POSTID", id1, "=")).getDBRules());
			this.postactionDao.deleteEntitys((new DBRule("POSTID", id1, "=")).getDBRules());
			this.postDao.deleteEntity(this.postDao.getEntity(id1));
		}

	}

	@Transactional
	public Post getPostEntity(String id) {
		return id == null ? null : this.postDao.getEntity(id);
	}

	@Transactional
	public DataQuery createPostSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery.init(query,
				"ALONE_AUTH_POST as post left join alone_auth_organization as org on post.ORGANIZATIONID=org.ID",
				"post.ID AS ID, post.EXTENDIS AS EXTENDIS, post. NAME AS NAME, post.ORGANIZATIONID AS ORGANIZATIONID, post.PSTATE AS PSTATE, post.EUSER AS EUSER, post.EUSERNAME AS EUSERNAME, post.CUSER AS CUSER, post.CUSERNAME AS CUSERNAME, post.ETIME AS ETIME, post.CTIME AS CTIME, org. NAME AS ORGNAME");
		return dbQuery;
	}

	@Transactional
	public void moveOrgTreeNode(String orgId, String targetOrgId) {
		String[] orgIds = orgId.split(",");

		for (int i = 0; i < orgIds.length; ++i) {
			Organization node = this.getOrganizationEntity(orgIds[i]);
			Organization target = this.getOrganizationEntity(targetOrgId);
			if (target.getTreecode().indexOf(node.getTreecode()) >= 0) {
				throw new RuntimeException("不能够移动到其子节点下!");
			}

			node.setParentid(targetOrgId);
			this.organizationDao.editEntity(node);
			List<Organization> list = this.organizationDao.getAllSubNodes(orgIds[i]);
			Iterator var9 = list.iterator();

			while (var9.hasNext()) {
				Organization org = (Organization) var9.next();
				this.initTreeCode(org.getId());
			}
		}

	}

	private void initTreeCode(String treeNodeId) {
		Organization node = this.getOrganizationEntity(treeNodeId);
		if (node.getParentid().equals("NONE")) {
			node.setTreecode(node.getId());
		} else {
			node.setTreecode(this.organizationDao.getEntity(node.getParentid()).getTreecode() + node.getId());
		}

		this.organizationDao.editEntity(node);
	}

	@Transactional
	public Post editPost(String postId, String postname, String extendis, LoginUser user) {
		Post post = this.postDao.getEntity(postId);
		post.setName(postname);
		post.setExtendis(extendis);
		post.setEtime(TimeTool.getTimeDate14());
		post.setEuser(user.getId());
		post.setEusername(user.getName());
		this.postDao.editEntity(post);
		this.userpostDao.deleteEntitys((new DBRule("POSTID", post.getId(), "=")).getDBRules());
		return post;
	}

	@Transactional
	public Post insertPost(String orgId, String postname, String extendis, LoginUser user) {
		Post post = new Post();
		post.setName(postname);
		post.setExtendis(extendis);
		post.setCtime(TimeTool.getTimeDate14());
		post.setCuser(user.getId());
		post.setCusername(user.getName());
		post.setEtime(TimeTool.getTimeDate14());
		post.setEuser(user.getId());
		post.setEusername(user.getName());
		post.setOrganizationid(orgId);
		post.setPstate("1");
		return this.postDao.insertEntity(post);
	}

	@Transactional
	public List<EasyUiTreeNode> loadPostTree(String ids) {
		if (ids == null || ids.trim().length() <= 0) {
			ids = "NONE";
		}

		DataQuery query = DataQuery.getInstance("1", "NAME,PARENTID,ID,UTYPE",
				"(SELECT NAME,PARENTID,ID,'11' AS UTYPE,SORT FROM alone_auth_organization  UNION SELECT NAME,ORGANIZATIONID AS PARENTID,ID,TYPE AS UTYPE,1000 as SORT FROM alone_auth_post  ) a ");
		query.setPagesize(1000);
		query.addRule(new DBRule("PARENTID", ids, "="));
		query.setNoCount();
		query.addSort(new DBSort("UTYPE", "asc"));
		query.addSort(new DBSort("SORT", "asc"));
		DataQuery query2 = DataQuery.getInstance("1",
				"a.NAME as NAME,a.PARENTID as PARENTID,a.ID as ID,a.UTYPE as UTYPE",
				"alone_auth_organization b LEFT JOIN (SELECT NAME,PARENTID,ID,'0' AS UTYPE FROM alone_auth_organization  UNION SELECT NAME,ORGANIZATIONID AS PARENTID,ID,TYPE AS UTYPE FROM alone_auth_post  ) a ON a.PARENTID=b.ID");
		query2.setPagesize(1000);
		query2.addRule(new DBRule("b.PARENTID", ids, "="));
		query2.setNoCount();
		List list = null;

		try {
			List<Map<String, Object>> listOne = query.search().getResultList();
			Iterator var7 = listOne.iterator();

			while (var7.hasNext()) {
				Map<String, Object> node = (Map) var7.next();
				if (node.get("UTYPE").equals("1")) {
					node.put("UTYPE", "icon-suppliers");
				}

				if (node.get("UTYPE").equals("2")) {
					node.put("UTYPE", "icon-user_medical");
				}
			}

			list = EasyUiTreeNode.formatAsyncAjaxTree(listOne, query2.search().getResultList(), "PARENTID", "ID",
					"NAME", "UTYPE");
			return list;
		} catch (SQLException var8) {
			throw new RuntimeException(var8);
		}
	}

	@Transactional
	public void addUserPost(String userId, String postId, LoginUser currentUser) {
	}

	public OrganizationDaoInter getOrganizationDao() {
		return this.organizationDao;
	}

	public void setOrganizationDao(OrganizationDaoInter dao) {
		this.organizationDao = dao;
	}

	public PostDaoInter getPostDao() {
		return this.postDao;
	}

	public PostactionDaoInter getPostactionDao() {
		return this.postactionDao;
	}

	public void setPostactionDao(PostactionDaoInter postactionDao) {
		this.postactionDao = postactionDao;
	}

	public void setPostDao(PostDaoInter postDao) {
		this.postDao = postDao;
	}

	public UserpostDaoInter getUserpostDao() {
		return this.userpostDao;
	}

	public void setUserpostDao(UserpostDaoInter userpostDao) {
		this.userpostDao = userpostDao;
	}

	public UserDaoInter getUserDao() {
		return this.userDao;
	}

	public void setUserDao(UserDaoInter userDao) {
		this.userDao = userDao;
	}

	@Transactional
	public void removePostUsers(String postId, String userid, LoginUser currentUser) {
		String[] userIds = userid.split(",");
		String[] var8 = userIds;
		int var7 = userIds.length;

		for (int var6 = 0; var6 < var7; ++var6) {
			String userId = var8[var6];
			this.userpostDao
					.deleteEntitys((new DBRule("USERID", userId, "=")).addRule("POSTID", postId, "=").getDBRules());
		}

	}

	@Transactional
	public void setPostActionTree(List<String> actionTreeIds, String postId) {
		if (postId != null && postId.trim().length() > 0) {
			this.postactionDao.deleteEntitys((new DBRule("POSTID", postId, "=")).getDBRules());
			Iterator var4 = actionTreeIds.iterator();

			while (var4.hasNext()) {
				String nodeId = (String) var4.next();
				Postaction postaction = new Postaction();
				postaction.setMenuid(nodeId);
				postaction.setPostid(postId);
				this.postactionDao.insertEntity(postaction);
			}

		} else {
			throw new IllegalArgumentException("请选择一个岗位");
		}
	}

	@Transactional
	public List<Organization> getTree() {
		return this.organizationDao.selectEntitys((new DBRule("1", "1", "=")).getDBRules());
	}

	public List<Map<String, Object>> getPostList(String orgId) {
		try {
			DataQuery query = DataQuery.getInstance(1,
					"POST.ID AS POSTID, POST.NAME AS POSTNAME, ORG.ID AS ORGID, ORG.NAME AS ORGNAME ",
					"ALONE_AUTH_POST POST INNER JOIN ALONE_AUTH_ORGANIZATION ORG ON POST.ORGANIZATIONID = ORG.ID");
			query.setNoCount();
			query.addRule(new DBRule("POST.ORGANIZATIONID", orgId, "="));
			DataResult result = query.search();
			List<Map<String, Object>> list = result.getResultList();
			return list;
		} catch (SQLException var5) {
			var5.printStackTrace();
			return null;
		}
	}

	@Transactional
	public List<Map<String, Object>> getPostListWithPOrgPost(String orgId) {
		if (orgId != null && !orgId.isEmpty()) {
			DataQuerys.wipeVirus(orgId);
			Organization entity = this.organizationDao.getEntity(orgId);
			String treecode = entity.getTreecode();
			String pOrgIds = "";

			for (int i = 1; i <= (treecode.length() - 32) / 32; ++i) {
				pOrgIds = pOrgIds + "'" + treecode.substring((i - 1) * 32, i * 32) + "'";
				if (i <= (treecode.length() - 64) / 32) {
					pOrgIds = pOrgIds + ",";
				}
			}

			if (pOrgIds.isEmpty()) {
				pOrgIds = "''";
			}

			try {
				DataQuery query = DataQuery.getInstance(1,
						"a.POSTID AS POSTID, a.POSTNAME AS POSTNAME, a.ORGID AS ORGID, a.ORGNAME AS ORGNAME ",
						"(SELECT PPOST.ID AS POSTID, PPOST.NAME AS POSTNAME, PORG.ID AS ORGID, PORG.NAME AS ORGNAME FROM ALONE_AUTH_ORGANIZATION PORG LEFT JOIN ALONE_AUTH_POST PPOST ON PORG.ID = PPOST.ORGANIZATIONID WHERE PPOST.EXTENDIS = '1' AND PORG.ID IN ("
								+ pOrgIds + ") /* 查找父机构可用的岗位 */" + "UNION ALL "
								+ "SELECT POST.ID AS POSTID, POST.NAME AS POSTNAME, ORG.ID AS ORGID, ORG.NAME AS ORGNAME "
								+ "FROM ALONE_AUTH_ORGANIZATION ORG "
								+ "LEFT JOIN ALONE_AUTH_POST POST ON ORG.ID = POST.ORGANIZATIONID " + "WHERE ORG.ID = '"
								+ orgId + "' /* 查找当前机构所有的岗位 */) a ");
				query.setNoCount();
				query.setPagesize(1000);
				query.addSqlRule("and  POSTID is not null");
				DataResult result = query.search();
				List<Map<String, Object>> list = result.getResultList();
				return list;
			} catch (SQLException var8) {
				var8.printStackTrace();
				return null;
			}
		} else {
			return new ArrayList();
		}
	}

	@Transactional
	public List<Organization> getParentOrgs(String orgid) {
		String id = orgid;
		ArrayList orgs = new ArrayList();

		while (id != null) {
			Organization centity = this.getOrganizationEntity(id);
			if (centity != null && centity.getParentid() != null && centity.getParentid().trim().length() > 0) {
				id = centity.getParentid();
			} else {
				id = null;
			}

			if (centity != null) {
				orgs.add(centity);
			}
		}

		Collections.reverse(orgs);
		return orgs;
	}

	public List<String> getOrgUsers(String orgid) {
		DataQuerys.wipeVirus(orgid);
		List<String> list = new ArrayList();
		DataQuery query = DataQuery.getInstance(1, "a.id as id ,a.name as name",
				"ALONE_AUTH_USER a left join ALONE_AUTH_USERORG b on b.USERID=a.id left join ALONE_AUTH_ORGANIZATION c on c.ID=b.ORGANIZATIONID");
		query.setPagesize(1000);
		Organization org = this.getOrganizationEntity(orgid);
		if (org == null) {
			log.error("一个组织机构id未找到对应的组织机构，应该是被删除了，但是此处返回一个空的数组！");
			return list;
		} else {
			query.addSqlRule(" and c.TREECODE like '" + org.getTreecode() + "%'");

			try {
				Iterator var6 = query.search().getResultList().iterator();

				while (var6.hasNext()) {
					Map<String, Object> node = (Map) var6.next();
					list.add((String) node.get("ID"));
				}

				return list;
			} catch (SQLException var7) {
				var7.printStackTrace();
				return list;
			}
		}
	}

	public List<String> getPostUser(String postid) {
		DataQuery query = DataQuery.getInstance(1, "POST.ID AS ID,USERPOST.USERID AS USERID",
				"ALONE_AUTH_POST AS POST LEFT JOIN ALONE_AUTH_USERPOST AS USERPOST ON POST.ID=USERPOST.POSTID");
		query.setPagesize(1000);
		query.addRule(new DBRule("post.ID", postid, "="));
		ArrayList list = new ArrayList();

		try {
			Iterator var5 = query.search().getResultList().iterator();

			while (var5.hasNext()) {
				Map<String, Object> node = (Map) var5.next();
				String userid = (String) node.get("USERID");
				if (userid != null) {
					list.add((String) node.get("USERID"));
				}
			}

			return list;
		} catch (SQLException var7) {
			var7.printStackTrace();
			return list;
		}
	}

	public List<Organization> getList() {
		return this.organizationDao.getList();
	}
}
